package anveshitha.queryexecutors;

import static anveshitha.config.AnveshithaConstants.FILE_SEPARATOR;
import static anveshitha.config.AnveshithaConstants.JAVA;
import static anveshitha.config.AnveshithaConstants.LUCENE_INDEX_DIR;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import anveshitha.analyzers.JavaSourceCodeAnalyzer;
import anveshitha.analyzers.KeywordAnalyzer;
import anveshitha.config.AnveshithaConstants.FieldEnum;


public class QueryExecutor {
	
	File fIndexDir;
	String fileExtn;
	Analyzer codeAnalyzer;
	
	public QueryExecutor(String fileExtn,Analyzer codeAnalyzer) {
		super();
		this.fileExtn = fileExtn;
		this.fIndexDir = new File(LUCENE_INDEX_DIR + fileExtn + FILE_SEPARATOR);
		this.codeAnalyzer = codeAnalyzer;
	}


	public void execute(String sQuery,boolean allowLeadingWildcard) throws IOException, ParseException{
		
		PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(codeAnalyzer);		
		analyzer.addAnalyzer(FieldEnum.IMPORT.name(), new KeywordAnalyzer());
		
		Directory fsDir;
		fsDir = FSDirectory.getDirectory(fIndexDir);
		IndexSearcher indexSearcher = new IndexSearcher(fsDir);
		QueryParser queryParser = new QueryParser(FieldEnum.CLASSNAME.name(),analyzer);
		queryParser.setAllowLeadingWildcard(allowLeadingWildcard);
		Query query = queryParser.parse(sQuery);
		
		long start = System.currentTimeMillis();
		System.out.println("Searching...");
		Hits hits = indexSearcher.search(query);
		long end = System.currentTimeMillis();

		System.out.println("Found " + hits.length() + " docs in "
				+ (end - start) + " millisec");

		//TODO: process hits and return in required formats
		for (int i = 0; i < hits.length(); i++) {
			Document doc = hits.doc(i);
			System.out.println(doc.get(FieldEnum.CLASSNAME.name()) + " with a score of "
					+ hits.score(i));
		}
		indexSearcher.close();
		
	}
	
	/** Main for running test case by itself. */
	public static void main(String args[]) {
		try {

			String q = "RETURNTYPE: \"int\" OR RETURNTYPE: String";
			QueryExecutor exe = new QueryExecutor(JAVA,new JavaSourceCodeAnalyzer());
			exe.execute(q,true);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
